package redisson.rest;

import java.util.HashMap;
import java.util.Map;

import org.redisson.api.RPatternTopic;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;

@Slf4j
//@RestController
@Order(Ordered.LOWEST_PRECEDENCE) // 保证晚
public class RTransactionRest implements SmartInitializingSingleton {

//	原因	现象	解决
//	先用 RTopic 监听通配符	订阅日志里只有 SUBSCRIBE 无 PSUBSCRIBE	换成 RPatternTopic
//	先发送后订阅	返回 clients=0 且收不到	调整顺序：先 addListener 再 publish
//	序列化对不上	静默丢弃，无异常	发送与监听都用同一 Codec 或同一类型

	@Autowired
	RedissonClient redissonClient;

	@Override
	public void afterSingletonsInstantiated() {

		//////////////////////必须先配置监听//////////////////////
		
		log.info("### 监听redisson消息,启动成功,,, ");
		// 通配符订阅一定要用 RPatternTopic
		RPatternTopic patternTopic = redissonClient.getPatternTopic("rpa:probe:*");
		patternTopic.addListener(Map.class, (pattern, channel, msg) -> {
			log.info(">>>> 收到 pattern={} channel={} msg={}", pattern, channel, msg);
		});
		log.info("### 模式订阅已建立");

		//////////////////////再提供发送消息//////////////////////
		// 再发送消息
		String str = "rpa:probe:%s";
		RTopic topic = redissonClient.getTopic(String.format(str, "axxc"));

		Map<Object, Object> map = new HashMap<>();
		map.put("AA", "AA");
		map.put("BB", "BB");
		map.put("CC", "CC");

		long publish = topic.publish(map);

		log.info("### 发送redisson消息成功,,, {} ", publish);

	}

}
